/* PostgreSQL */
#include <postgres.h>
#include <fmgr.h>

/* CURL */
#include <curl/curl.h>

/* Set up PgSQL */
PG_MODULE_MAGIC;

/* Function signatures */
void _PG_init(void);
void _PG_fini(void);
static size_t http_writeback(void *contents, size_t unit, size_t length, void *userp);

/* Startup */
void _PG_init(void) {	
	curl_global_init(CURL_GLOBAL_ALL);
}

/* Tear-down */
void _PG_fini(void) {
	curl_global_cleanup();
}

/**
* This function is passed into CURL as the CURLOPT_WRITEFUNCTION,
* this allows the  return values to be held in memory, in our case in a string.
*/
static size_t
http_writeback(void *contents, size_t unit, size_t length, void *userp) {
	return unit * length;
}

/**
* Master HTTP request function, takes in an http_request tuple and outputs
* an http_response tuple.
*/
Datum http_notify(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(http_notify);
Datum http_notify(PG_FUNCTION_ARGS) {

	CURL* curl = NULL;
	struct curl_slist *headers = NULL;
	int http_return;

	text *url, *content;

	curl = curl_easy_init();

	/* Set the target URL */
	url = PG_GETARG_TEXT_P(0);
	curl_easy_setopt(curl, CURLOPT_URL, VARDATA(url));

	/* Set the user agent */
	curl_easy_setopt(curl, CURLOPT_USERAGENT, "Pisces 1.0.0");

	/* Add the content to the payload */
	// curl_easy_setopt(curl, CURLOPT_POST, 1);
	curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PATCH");

	/* Keep sockets held open */
	curl_easy_setopt(curl, CURLOPT_FORBID_REUSE, 0);
	/* Add a keep alive option to the headers to reuse network sockets */
	headers = curl_slist_append(headers, "Connection: Keep-Alive");

	/* Let our charset preference be known */
	headers = curl_slist_append(headers, "Charsets: utf-8");

	/* json */
	headers = curl_slist_append(headers, "Content-Type: application/json");

	/* Set the headers */
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_writeback);

	/* Set up the HTTP timeout */
	curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, 3000);
	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 1);

	content = PG_GETARG_TEXT_P(1);
	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, VARDATA(content));

	http_return = curl_easy_perform(curl);

	curl_easy_cleanup(curl);

	/* Return */
	PG_RETURN_BOOL(http_return == CURLE_OK);
}

// Local Variables:
// mode: C++
// tab-width: 4
// c-basic-offset: 4
// indent-tabs-mode: t
// End:
